package com.oceanstar.springboot.controller;

import com.oceanstar.springboot.mapper.mapper;
import com.oceanstar.springboot.pojo.entity.Student;
import com.oceanstar.springboot.pojo.vo.Result;
import com.oceanstar.springboot.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@Slf4j
public class Controller {

    @Autowired
    private mapper mapper;
    
    @Autowired
    private StudentService studentService;

    @GetMapping("/list")
    public Result<List<Student>> list() {
        Result<List<Student>> result = Result.success(studentService.hello());
        log.info("/list{}", result);
        return result;
    }
    
    /**
     * 根据ID查询学生
     */
    @GetMapping("/student/{id}")
    public Result<Student> getStudentById(@PathVariable Integer id) {
        try {
            Student student = studentService.getStudentById(id);
            if (student != null) {
                return Result.success(student);
            } else {
                return Result.error("未找到该学生");
            }
        } catch (Exception e) {
            log.error("查询学生失败", e);
            return Result.error("查询学生失败");
        }
    }
    
    /**
     * 添加学生
     */
    @PostMapping("/student")
    public Result<String> addStudent(@RequestBody Student student) {
        try {
            studentService.addStudent(student);
            return Result.success("添加成功");
        } catch (Exception e) {
            log.error("添加学生失败", e);
            return Result.error("添加学生失败");
        }
    }
    
    /**
     * 更新学生信息
     */
    @PutMapping("/student")
    public Result<String> updateStudent(@RequestBody Student student) {
        try {
            studentService.updateStudent(student);
            return Result.success("更新成功");
        } catch (Exception e) {
            log.error("更新学生失败", e);
            return Result.error("更新学生失败");
        }
    }
    
    /**
     * 删除学生
     */
    @DeleteMapping("/student/{id}")
    public Result<String> deleteStudent(@PathVariable Integer id) {
        try {
            studentService.deleteStudent(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除学生失败", e);
            return Result.error("删除学生失败");
        }
    }
}